import type { PluginContext, PluginAPI } from '../../../modules/plugin/types';
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
import { getDiagnosticService } from '../../../services/diagnosticService';

export function activate(context: PluginContext, api: PluginAPI) {
  console.log('Activating diagnostic-demo plugin...');

  // 添加一个命令来创建演示问题
  const createDemoProblemsDisposable = api.commands.registerCommand('diagnostic-demo.createProblems', () => {
    // 获取当前所有模型
    const models = monaco.editor.getModels();
    
    if (models.length === 0) {
      api.window.showInformationMessage('没有打开的文件。请先打开一个 TypeScript 或 JavaScript 文件。');
      return;
    }

    // 为第一个模型添加一些演示问题
    const model = models[0];
    
    const demoMarkers: monaco.editor.IMarkerData[] = [
      {
        severity: monaco.MarkerSeverity.Error,
        startLineNumber: 1,
        startColumn: 1,
        endLineNumber: 1,
        endColumn: 10,
        message: '演示错误：未定义的变量',
        source: 'diagnostic-demo'
      },
      {
        severity: monaco.MarkerSeverity.Warning,
        startLineNumber: 2,
        startColumn: 1,
        endLineNumber: 2,
        endColumn: 15,
        message: '演示警告：未使用的变量',
        source: 'diagnostic-demo'
      },
      {
        severity: monaco.MarkerSeverity.Info,
        startLineNumber: 3,
        startColumn: 1,
        endLineNumber: 3,
        endColumn: 20,
        message: '演示信息：建议使用 const 而不是 let',
        source: 'diagnostic-demo'
      }
    ];

    // 设置标记
    try {
      getDiagnosticService().setModelMarkers(model, demoMarkers);
    } catch (error) {
      console.error('Failed to set markers:', error);
      api.window.showInformationMessage('诊断服务尚未就绪，请稍后重试。');
      return;
    }
    
    api.window.showInformationMessage(`已为文件 ${model.uri.path} 添加 ${demoMarkers.length} 个演示问题，请查看底部问题面板。`);
  });
  context.subscriptions.push(createDemoProblemsDisposable);

  // 添加一个命令来清除所有问题
  const clearProblemsDisposable = api.commands.registerCommand('diagnostic-demo.clearProblems', () => {
    // 清除所有模型的标记
    const models = monaco.editor.getModels();
    models.forEach(model => {
      monaco.editor.setModelMarkers(model, 'diagnostic-demo', []);
    });
    
    try {
      getDiagnosticService().collectProblems();
    } catch (error) {
      console.warn('Failed to collect problems:', error);
    }
    api.window.showInformationMessage('已清除所有演示问题。');
  });
  context.subscriptions.push(clearProblemsDisposable);

  // 添加一个命令来检测TypeScript错误
  const detectTsErrorsDisposable = api.commands.registerCommand('diagnostic-demo.detectTsErrors', () => {
    const models = monaco.editor.getModels();
    const tsModels = models.filter(model => {
      const path = model.uri.path;
      return path.endsWith('.ts') || path.endsWith('.js') || path.endsWith('.tsx') || path.endsWith('.jsx');
    });

    if (tsModels.length === 0) {
      api.window.showInformationMessage('没有找到 TypeScript 或 JavaScript 文件。');
      return;
    }

    let totalProblems = 0;
    tsModels.forEach(model => {
      const content = model.getValue();
      const lines = content.split('\n');
      const markers: monaco.editor.IMarkerData[] = [];

      lines.forEach((line, index) => {
        const lineNumber = index + 1;
        
        // 检测常见的 TypeScript 问题
        
        // 1. 检测未声明的变量（简单的正则匹配）
        const undeclaredVarMatch = line.match(/console\.log\((\w+)\)/);
        if (undeclaredVarMatch && !content.includes(`let ${undeclaredVarMatch[1]}`) && !content.includes(`const ${undeclaredVarMatch[1]}`) && !content.includes(`var ${undeclaredVarMatch[1]}`)) {
          markers.push({
            severity: monaco.MarkerSeverity.Error,
            startLineNumber: lineNumber,
            startColumn: line.indexOf(undeclaredVarMatch[1]) + 1,
            endLineNumber: lineNumber,
            endColumn: line.indexOf(undeclaredVarMatch[1]) + undeclaredVarMatch[1].length + 1,
            message: `变量 '${undeclaredVarMatch[1]}' 未声明`,
            source: 'diagnostic-demo-ts'
          });
        }

        // 2. 检测缺少分号
        if (line.trim() && !line.trim().endsWith(';') && !line.trim().endsWith('{') && !line.trim().endsWith('}') && !line.includes('//')) {
          const trimmedLine = line.trim();
          if (trimmedLine.match(/^(let|const|var|return|throw)\s+/)) {
            markers.push({
              severity: monaco.MarkerSeverity.Warning,
              startLineNumber: lineNumber,
              startColumn: line.length,
              endLineNumber: lineNumber,
              endColumn: line.length + 1,
              message: '缺少分号',
              source: 'diagnostic-demo-ts'
            });
          }
        }

        // 3. 检测类型错误（简单示例）
        const typeErrorMatch = line.match(/(let|const)\s+(\w+):\s*number\s*=\s*["']/);
        if (typeErrorMatch) {
          markers.push({
            severity: monaco.MarkerSeverity.Error,
            startLineNumber: lineNumber,
            startColumn: line.indexOf('=') + 1,
            endLineNumber: lineNumber,
            endColumn: line.length,
            message: `类型 'string' 不能赋值给类型 'number'`,
            source: 'diagnostic-demo-ts'
          });
        }
      });

      if (markers.length > 0) {
        try {
          getDiagnosticService().setModelMarkers(model, markers);
          totalProblems += markers.length;
        } catch (error) {
          console.warn('Failed to set markers for model:', error);
        }
      }
    });

    if (totalProblems > 0) {
      api.window.showInformationMessage(`检测到 ${totalProblems} 个问题，请查看问题面板。`);
    } else {
      api.window.showInformationMessage('没有检测到问题。');
    }
  });
  context.subscriptions.push(detectTsErrorsDisposable);

  console.log('Diagnostic demo plugin activated!');
}

export function deactivate() {
  console.log('Deactivating diagnostic-demo plugin...');
}